//TCPTest.java
package com.ylaihui.net;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest1 {
    @Test
    public void serverTest() throws IOException {
        ServerSocket ss = new ServerSocket(65500);

        System.out.println("accepting...");
        Socket accept = ss.accept();

        InputStream is = accept.getInputStream();

        // 客户端发出的消息有汉字的情况
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[10];
        int len = 0;
        while ((len = is.read(bytes)) != -1){
            baos.write(bytes,0,len);
        }
        System.out.println(baos);

        is.close();
        accept.close();
        ss.close();
    }

    @Test
    public void clientTest() throws IOException {
        InetAddress localhost = InetAddress.getByName("localhost");
        Socket socket = new Socket(localhost, 65500);

        OutputStream os = socket.getOutputStream();
        os.write("这里是客户端".getBytes());

        os.close();
        socket.close();
    }
}
